<template>
  <el-dialog
    width="980px"
    title="申请退款"
    :visible="value"
    @close="handleClose"
  >
    <el-form inline>
      <el-form-item label="开单TC">{{ data.yiyaBillingMain.tc }}</el-form-item>
    </el-form>
    <el-table
      border
      stripe
      :data="data.yiyaItemBillingExtends"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column
        label="项目名称"
        align="center"
        prop="itemName"
        min-width="160"
      ></el-table-column>
      <el-table-column label="数量/单位" align="center" prop="count">
        <span slot-scope="scope">
          {{ scope.row.count }} {{ scope.row.unit }}
        </span>
      </el-table-column>
      <el-table-column
        label="应收（元）"
        align="center"
        prop="paidInAmount"
      ></el-table-column>
      <el-table-column
        label="已收（元）"
        align="center"
        prop="paidInAmount"
      ></el-table-column>
      <el-table-column
        label="现金退费（元）"
        align="center"
        prop="refundPayAmount"
        min-width="120"
      >
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.selection"
            :value="scope.row.refundPayAmount"
            @input="handleRefundPayAmountInput($event, scope.row)"
            @blur="handleRefundPayAmountBlur(scope.row)"
          ></el-input>
          <span v-else>
            {{ scope.row.refundPayAmount }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="储值退费（元）"
        min-width="120"
        align="center"
        prop="refundPetCardAmount"
      >
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.selection"
            :value="scope.row.refundPetCardAmount"
            @input="handleRefundPetCardAmountInput($event, scope.row)"
            @blur="handleRefundPetCardAmountBlur(scope.row)"
          ></el-input>
          <span v-else>
            {{ scope.row.refundPetCardAmount }}
          </span>
        </template>
      </el-table-column>
    </el-table>
    <el-card class="mt20" shadow="never" :body-style="{ paddingBottom: 0 }">
      <el-form inline>
        <el-form-item label="应收金额">
          {{ data.total.paidInAmount }}
        </el-form-item>
        <el-form-item label="退款">
          {{ thisPay }}
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="mt20" shadow="never" :body-style="{ paddingBottom: 0 }">
      <el-form inline>
        <el-form-item label="备注">
          <el-input
            v-model="remarks"
            style="width: 500px"
            :autosize="{ minRows: 4, maxRows: 8 }"
            type="textarea"
            placeholder="请输入内容"
          >
          </el-input>
        </el-form-item>
      </el-form>
    </el-card>
    <template slot="footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button
        type="primary"
        :disabled="thisPay === '0.00'"
        :loading="loading"
        @click="handleSubmit"
      >
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
import { mapState } from 'vuex'
import { againBilling } from '@/api/services/billingMain'
import { billingTypeEnum } from '@/utils/enums'

export default {
  name: 'RefundApplication',
  model: {
    prop: 'value',
    event: 'close',
  },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
      default: () => ({
        yiyaBillingMain: {},
        yiyaItemBillingExtends: [],
        total: {},
      }),
    },
  },
  data() {
    return {
      loading: false,
      remarks: '',
      multipleSelection: [],
    }
  },
  computed: {
    ...mapState({
      userName: (state) => state.user.name,
    }),
    refundPayAmount() {
      return this.data.yiyaItemBillingExtends
        .reduce((total, { refundPayAmount }) => total + +refundPayAmount, 0)
        .toFixed(2)
    },
    refundPetCardAmount() {
      return this.data.yiyaItemBillingExtends
        .reduce(
          (total, { refundPetCardAmount }) => total + +refundPetCardAmount,
          0
        )
        .toFixed(2)
    },
    thisPay() {
      return (+this.refundPayAmount + +this.refundPetCardAmount).toFixed(2)
    },
  },
  watch: {
    value(val) {
      if (val) {
        this.init()
      }
    },
  },
  methods: {
    init() {
      this.data.yiyaItemBillingExtends = this.data.yiyaItemBillingExtends.map(
        (item) => {
          return {
            ...item,
            selection: false,
            refundPayAmount: 0,
            refundPetCardAmount: 0,
            costPrice: item.paidInPrice,
          }
        }
      )
    },
    handleClose() {
      this.$emit('close', false)
    },
    handleRefundPayAmountInput(e, project) {
      if (isNaN(+e)) {
        return
      }
      project.refundPayAmount = e || 0
    },
    handleRefundPayAmountBlur(project) {
      const { payAmount, refundPayAmount } = project
      project.refundPayAmount = Math.min(+payAmount, +refundPayAmount)
    },
    handleRefundPetCardAmountInput(e, project) {
      if (isNaN(+e)) {
        return
      }
      project.refundPetCardAmount = e || 0
    },
    handleRefundPetCardAmountBlur(project) {
      const { petCardAmount, refundPetCardAmount } = project
      project.refundPetCardAmount = Math.min(
        +petCardAmount,
        +refundPetCardAmount
      )
    },
    async handleSubmit() {
      await this.$confirm('是否确认退款?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      try {
        this.loading = true
        const { id } = this.data.yiyaBillingMain
        const formData = {
          billingPerson: this.userName,
          thisPay: this.thisPay,
          type: billingTypeEnum['退款'],
          billingRemarks: this.remarks,
          // arrearageChange: this.thisPay,
          // personArrearage: this.newOwingPrice,
          yiyaBillingMain: {
            id,
          },
          yiyaItemBillingExtends: this.data.yiyaItemBillingExtends.map(
            (item) => {
              return {
                id: item.id,
                thisPay: +item.refundPayAmount,
                storedDeductPrice: item.refundPetCardAmount,
              }
            }
          ),
        }
        await againBilling(formData)
        this.msgSuccess('开单成功')
        this.handleClose()
        this.$emit('ok')
      } finally {
        this.loading = false
      }
    },
    handleSelectionChange(val) {
      this.data.yiyaItemBillingExtends.forEach((item) => {
        if (val.indexOf(item) !== -1) {
          item.selection = true
        } else {
          item.selection = false
          item.refundPayAmount = 0
          item.refundPetCardAmount = 0
          item.costPrice = item.paidInPrice
        }
      })
      this.multipleSelection = val
    },
  },
}
</script>

<style>
.el-drawer__body {
  padding: 20px;
}
</style>
